package com.huan.dao;

import com.huan.util.ConfigManager;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;

public class BaseDao {

    private Connection conn;
    private PreparedStatement pstmt; // 预防sql注入
    private ResultSet rs;

    /**
     * 抽取公用代码块1 - 获取数据库连接
     *
     * @return
     */
    public boolean getConnection()
    {
        String driver = ConfigManager.getInstance().getString("jdbc.driver");
        String url = ConfigManager.getInstance().getString("jdbc.url");
        String userName = ConfigManager.getInstance().getString("jdbc.username");
        String password = ConfigManager.getInstance().getString("jdbc.password");

        try {
            // 1.加载驱动程序
            Class.forName(driver);
            // 2.获取数据库链接
            conn = DriverManager.getConnection(url, userName, password);
            return true;
        }
        catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     */
    public boolean getConnectionFromPool()
    {

        try {
            Context context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/news");
            conn=dataSource.getConnection();
            return true;
        }
        catch (NamingException | SQLException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 抽取公共代码2 - 关闭资源
     *
     * @return
     */
    public boolean closeResource()
    {
        // 5.释放资源
        try {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            if (conn != null)
                conn.close();
            return true;
        }
        catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    /**
     * 增、删、改的公用代码
     *
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdate(String sql, Object[] params)
    {
        int rows = 0;
        if (getConnection()) {
            try {
                execute(sql, params);
                rows = pstmt.executeUpdate();
            }
            catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            finally {
                closeResource();
            }
        }
        return rows;
    }

    /**
     * 执行查询的公共代码
     *
     * @param sql
     * @param params
     * @return
     */
    public ResultSet executeSQL(String sql, Object[] params)
    {
        int rows = 0;
        if (getConnection()) {
            try {
                execute(sql, params);
                rs = pstmt.executeQuery();
            }
            catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return rs;
    }

    /**
     * 向SQL语句传入参数
     *
     * @param sql
     * @param params
     * @throws SQLException
     */
    private void execute(String sql, Object[] params) throws SQLException
    {
        pstmt = conn.prepareStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                if (params[i] instanceof Integer)
                    pstmt.setInt(i + 1, (Integer) params[i]);
                if (params[i] instanceof String)
                    pstmt.setString(i + 1, (String) params[i]);
                if (params[i] instanceof Timestamp)
                    pstmt.setTimestamp(i + 1, (Timestamp) params[i]);
            }
        }
    }
}
